<template>
  <uni-popup ref="popup" type="bottom" background-color="#fff">
    <!-- 一般性的list底部弹出框 -->
    <view class="popup-content">
      <view class="popup-header">
        <text class="popup-title">{{ title }}</text>
        <text class="popup-close" @click="close">×</text>
      </view>

      <!-- 搜索区域 -->
      <view class="search-wrapper" v-if="!!props.searchFunction">
        <up-input
          v-model="info.query.spell"
          placeholder="请输入"
          clearable
          @change="filterContent"
          class="h-full"
        ></up-input>
      </view>

      <scroll-view
        class="popup-body"
        scroll-y
        @scrolltolower="loadMore"
        @scrolltoupper="refreshContent"
      >
        <view
          v-for="(item, index) in info.list"
          :key="index + item.value"
          class="popup-item"
          :class="{ active: item.value === selectValue }"
          @click="select(item)"
        >
          {{ item.showname }}
        </view>

        <!-- 显示更多 -->
        <view
          v-show="!!props.isPaging && !info.queryError"
          class="text-center mt-10"
        >
          <uni-load-more :status="info.loadStatus" />
        </view>

        <up-empty v-show="info.queryError" mode="search"></up-empty>
      </scroll-view>
    </view>
  </uni-popup>
</template>

<script setup>
import { watch } from 'vue';
import utils from '@/common/js/utils/index.js';

const popup = ref(null);

const props = defineProps({
  title: {
    type: String,
    default: '选择',
  },
  //提交的字段
  submitKey: {
    type: String,
    default: '',
  },
  options: {
    type: [Array, Function],
    default: () => [],
  },
  selectValue: {
    type: [String, Number, null],
    default: null,
  },
  // 是否分页,source为空时，分页无效
  isPaging: {
    type: [Boolean, null],
    default: null,
  },
  // 搜索fn
  searchFunction: {
    type: [Function, null],
    default: null,
  },
});

const info = reactive({
  spell: '',
  loadStatus: 'noMore', // more、loading、noMore
  list: [],
  query: {
    spell: '',
    page: 1,
    number: 20,
  },
  count: 0, // 总条数
  queryError: false, //是否查询出错
});

const open = () => popup.value.open('bottom');
const close = () => popup.value.close();

const emit = defineEmits(['select', 'update:modelValue']);

const select = (item) => {
  emit('select', item, props.submitKey);
  close();
};

// 顶部的搜索
const filterContent = utils.debounce((val) => {
  if (props.searchFunction) {
    info.query.page = 1;
    info.list = [];
    info.loadStatus = 'more';
    getList();
  }
}, 300);

const loadMore = () => {
  if (props.searchFunction) {
    getList();
  }
};
const refreshContent = () => {
  if (props.searchFunction) {
    info.query.page = 1;
    info.list = [];
    info.loadStatus = 'more';
    getList();
  }
};

const getList = () => {
  if (props.searchFunction) {
    if (!!props.isPaging && info.loadStatus === 'noMore') {
      return false;
    }
    // console.log(`当前正在进行第${info.query.page}页数据加载`);
    props
      .searchFunction(info.query)
      .then((res) => {
        // console.log('搜索的返回值', res);
        // console.log('是否分页', !!props.isPaging);
        if (!!props.isPaging) {
          // 如果说是分页
          if (res.code == '0') {
            info.list = [...info.list, ...res.data];
            info.count = res.count;
            if (info.count > info.list.length) {
              info.loadStatus = 'more';
            } else {
              info.loadStatus = 'noMore';
            }
            info.query.page++;
          } else {
            uni.showToast({
              title: res.msg || '加载失败‘',
              icon: 'none',
            });
            // info.loadStatus = 'noMore';
          }

          // 下面是备品备件没有分页，临时模拟，后面拆掉 2024年09月02日19:22:21
          // info.list = [...info.list, ...res];
          // info.count = 60;
          // if (info.count > info.list.length) {
          //   info.loadStatus = 'more';
          // } else {
          //   info.loadStatus = 'noMore';
          // }
          // info.query.page++;
          // if (info.list.length === 0) {
          //   info.queryError = true;
          // }
        } else {
          // 不分页
          info.list = res;
        }
      })
      .catch((err) => {
        console.log(`materialsCode err`, err);
        info.list = [];
        info.loadStatus = 'noMore';
        info.queryError = true;
      });
  } else {
    console.log('没有触发对应的事件');
  }
};

watch(
  () => props.options,
  (newVal) => {
    info.list = props.options;
    info.queryError = info.list.length === 0;
  },
  {
    deep: true,
    immediate: true,
  }
);

onMounted(() => {
  if (props.searchFunction) {
    info.loadStatus = 'more';
    getList();
  }
});

defineExpose({
  open,
  close,
});
</script>

<style lang="scss" scoped>
.popup-content {
  background-color: #fff;
  border-top-left-radius: 20rpx;
  border-top-right-radius: 20rpx;
  overflow: hidden;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10rpx 20rpx 10rpx 15rpx;
  border-bottom: 1rpx solid #eee;
}

.popup-title {
  font-size: 24rpx;
  font-weight: bold;
}

.popup-close {
  font-size: 35rpx;
  color: #999;
}

.search-wrapper {
  margin: 10px 0 10px 0;
  padding: 0 12px;
  height: 34px;
}

.popup-body {
  max-height: 55vh;
  min-height: 55vh;

  .popup-item {
    padding: 14rpx 20rpx;
    border-top: 1rpx solid #e5e5e5;

    &:last-child {
      border-bottom: 1rpx solid #e5e5e5;
    }

    &.active {
      color: #f00;
    }
  }
}
</style>
